// preload.js
const { contextBridge, ipcRenderer } = require('electron');

// 将安全的方法暴露给渲染进程
contextBridge.exposeInMainWorld('electronAPI', {
    getAppInfo: () => ipcRenderer.invoke('get-app-info'),
    getConfig: () => ipcRenderer.invoke('get-config'),
    fetchRiver: (payload) => ipcRenderer.invoke('fetch-river', payload),
    fetchAllStationsNow: () => ipcRenderer.invoke('fetch-all-stations-now'),
    getLatestStations: () => ipcRenderer.invoke('get-latest-stations'),
    getWeather: () => ipcRenderer.invoke('fetch-weather'),
    onlineStatus: () => navigator.onLine,
    subscribeOnline: (handler) => {
        const listener = () => handler(navigator.onLine);
        window.addEventListener('online', listener);
        window.addEventListener('offline', listener);
        return () => {
            window.removeEventListener('online', listener);
            window.removeEventListener('offline', listener);
        };
    },
    onRefreshNow: (handler) => {
        const listener = () => handler();
        ipcRenderer.on('refresh-now', listener);
        return () => ipcRenderer.removeListener('refresh-now', listener);
    },
    // 渲染端日志打到主进程文件
    writeLog: (level, message, meta) => ipcRenderer.invoke('renderer-write-log', { level, message, meta }),
    // 数据库相关API
    getDutyData: (date, useMockData) => ipcRenderer.invoke('get-duty-data', date, useMockData),
    getDutyConfig: () => ipcRenderer.invoke('get-duty-config'),
    testDbConnection: () => ipcRenderer.invoke('test-db-connection')
});